﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Collections;
using Microsoft.Win32;

namespace eBirdAttend
{
    public partial class EmployeeShift : UserControl
    {
        SqlConnection _sqlcon;
        SqlCommand _sqlcmd;
        DataSet ds;
        DataSet ds1;
        DataTable dt;
        DataTable dt1;
        SqlDataAdapter _sqladt;
        SqlDataReader _sqldr;
        ArrayList _arrEmpID = new ArrayList();
        ArrayList _arrMastCode=new ArrayList();
        string _strCon;
        #region Properties
        int _shiftCode;
        public int ShiftCode
        {
            get { return _shiftCode; }
            set { _shiftCode = value; }
        }        
        
      
        #endregion Properties

        private static bool _recursion = false;        
        //string _strCon =  Properties.Settings.Default.constr;
        public EmployeeShift()
        {
            InitializeComponent();
        }      
        
        private void EmployeeShift_Load(object sender, EventArgs e)
        {
            FillConnectionStr();
            SelectShift();
            SelectEmployee();
        }

        private void FillConnectionStr()
        {
            //Connection string stored in REgistry
            RegistryKey regKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\eBird\\eOffice1.0");
            if (regKey != null)
            {
                _strCon = regKey.GetValue("ConctString").ToString();
            }
        }

        private void SelectEmployee()
        {
            try
            {
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcmd.CommandText = "select distinct (EmpFirstName + ' ' + EmpLastName) as Name,EmpId from EmployDetails";
                _sqladt = new SqlDataAdapter(_sqlcmd);
                ds = new DataSet();
                _sqladt.Fill(ds);
                _sqlcon.Close();

                chkEmployList.Items.Clear();
                if(ds.Tables[0].Rows.Count > 0)
                chkEmployList.Items.Add("(All)");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    chkEmployList.Items.Add(dr[0], CheckState.Unchecked);
                    //chkEmployList.Items.Add(dr[1],CheckState.Unchecked);      
                }
            }
            catch (SqlException ex)
            {
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite(ex.Message.ToString());
            }

        }

        private void chkEmployList_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            // Recursion breaker (calling SetItemCheckState will re-fire this event)
            if (_recursion)
                return;

            _recursion = true;

            // If the "(All)" item is clicked, apply the new value to all items
            if (e.Index == 0)
                CheckAllItems(e.NewValue);

            // If any item is unchecked, then uncheck the "all" item
            else if (e.NewValue == CheckState.Unchecked)
                chkEmployList.SetItemCheckState(0, e.NewValue);

            _recursion = false;
        }

        private void CheckAllItems(CheckState value)
        {
            for (int i = 0; i < chkEmployList.Items.Count; i++)
            {
                chkEmployList.SetItemCheckState(i, value);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            lstEmploy.Items.Clear();
            foreach (int i in chkEmployList.CheckedIndices)
            {
                if(!chkEmployList.Items[i].ToString().Contains("All"))
                lstEmploy.Items.Add(chkEmployList.Items[i].ToString());
                //lstEmploy.Items.Remove("(ALL)");
            }
            if(lstEmploy.Items.Count>0)
            panel2.Visible = true;
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (lstEmploy.Items.Count > 0)
            {
                foreach (int i in lstEmploy.SelectedIndices)
                {
                    object itemToRemove = lstEmploy.Items[i];
                    lstEmploy.Items.Remove(itemToRemove);
                }
            }
            else
            {
                MessageBox.Show("No items found.");
            }
            //if (lstEmploy.Items.Count > 0)
            //    panel2.Visible = true;
            //else
            //    panel2.Visible = false;
        }

        private void SelectShift()
        {
            try
            {
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcmd.CommandText = "select ShName,ShId from ShiftDetails";
                _sqladt = new SqlDataAdapter(_sqlcmd);
                ds = new DataSet();
                _sqladt.Fill(ds);
                if (ds == null)
                {
                    return;
                }
                int i = (ds.Tables[0].Rows.Count) - 1;
                dt1 = new DataTable();
                DataRow dr1;
                dt1.Columns.Add("ShName");
                dt1.Columns.Add("ShID");
                dr1 = dt1.NewRow();
                dr1["ShName"] = "ALL";
                dr1["ShID"] = 0;
                dt1.Rows.Add(dr1);
                while (i >= 0)
                {
                    dr1 = dt1.NewRow();
                    dr1["ShName"] = ds.Tables[0].Rows[i][0];
                    dr1["ShID"] = ds.Tables[0].Rows[i][1];
                    dt1.Rows.Add(dr1);
                    i--;
                }

                BindingSource BindingSource1 = new BindingSource();
                BindingSource1.DataSource = dt1.DefaultView;
                BindingSource BindingSource2 = new BindingSource();
                BindingSource2.DataSource = BindingSource1;
                cmbShiftWise.DataSource = BindingSource1;
                cmbShiftWise.DisplayMember = dt1.Columns[0].ColumnName;
                cmbShiftWise.ValueMember = dt1.Columns[1].ColumnName;
                cmbShiftWise.Text = dt1.Rows[0][0].ToString();
                cmbShiftWise.SelectedValue = dt1.Rows[0][1];
                cmbShift.DataSource = BindingSource2;
                cmbShift.DisplayMember = dt1.Columns[0].ColumnName;
                cmbShift.ValueMember = dt1.Columns[1].ColumnName;
                cmbShift.Text = dt1.Rows[0][0].ToString();
                cmbShift.SelectedValue = dt1.Rows[0][1];
                _sqlcon.Close();
            }
            catch (SqlException ex)
            {
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite(ex.Message.ToString());
            }        
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (lstEmploy.Items.Count > 0)
            {
                if (cmbShift.Text == "ALL")
                {
                    MessageBox.Show("Please select the shift");
                    return;
                }
                if (lstEmploy.Items.ToString() == "(ALL)")
                    return;
                SelectEmpID();
                ShiftSaved();
            }
            else
            {
                MessageBox.Show("Please select the employees");
            }
        }
        

        private void SelectEmpID()
        {
            try
            {
                _arrEmpID.Clear();
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcon.Open();
                for (int i = 0; i < lstEmploy.Items.Count; i++)
                {
                    _sqlcmd.CommandText = "select EmpId from EmployDetails where (EmpFirstName + ' ' + EmpLastName) like '%" + lstEmploy.Items[i].ToString().Trim() + "%'";
                    _sqldr = _sqlcmd.ExecuteReader();
                    while (_sqldr.Read())
                    {
                        _arrEmpID.Add(_sqldr[0].ToString());                        
                    }
                    _sqldr.Close();
                }
                _sqlcon.Close();
            }
            catch (SqlException ex)
            {
                if (!_sqldr.IsClosed)
                    _sqldr.Close();
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite(ex.Message.ToString());
            }
        }

        private void ShiftSaved()
        {
            try
            {


                for (int i = 0; i < _arrEmpID.Count; i++)
                {
                    if (CheckShiftStatus(_arrEmpID[i].ToString()))
                    {
                        if (!_sqldr.IsClosed)
                            _sqldr.Close();
                        _sqlcon = new SqlConnection(_strCon);
                        _sqlcmd = new SqlCommand();
                        _sqlcmd.Connection = _sqlcon;

                        _sqlcon.Open();
                        _sqlcmd.CommandText = "update EmployDetails set EmpShiftid = '" + cmbShift.SelectedValue + "' where EmpID = '" + _arrEmpID[i].ToString() + "' ";
                        _sqlcmd.ExecuteNonQuery();
                        _sqlcon.Close();

                    }
                   
                }
                MessageBox.Show("Shift Assigned Successfully");
                lstEmploy.Items.Clear();
                SelectShift();
                SelectEmployee();
                CheckAllItems(CheckState.Unchecked);
            }
            catch (SqlException ex)
            {
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
            }
        }
        
        private bool CheckShiftStatus(string _strEmpID)
        {

            try
            {
                _sqlcon = new SqlConnection(_strCon);
                _sqlcmd = new SqlCommand();
                _sqlcmd.Connection = _sqlcon;
                _sqlcon.Open();
                _sqlcmd.CommandText = "select EmpID from EmployDetails where EmpID= '" + _strEmpID + "'";
                _sqldr = _sqlcmd.ExecuteReader();
                if (_sqldr.Read())
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                if (_sqlcon.State == ConnectionState.Open)
                    _sqlcon.Close();
                LogWrite(ex.Message.ToString());
                return false;
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void btnRemovAll_Click(object sender, EventArgs e)
        {
            lstEmploy.Items.Clear();            
        }

        private void cmbShiftWise_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbShiftWise.Text != "ALL")
            {
                chkEmployList.Items.Clear();
                try
                {
                    _sqlcon = new SqlConnection(_strCon);
                    _sqlcmd = new SqlCommand();
                    _sqlcmd.Connection = _sqlcon;
                    _sqlcmd.CommandText = "select distinct (EmpFirstName + ' ' + EmpLastName) as Name,EmpId from EmployDetails where EmpShiftId='" + cmbShiftWise.SelectedValue + "'";
                    _sqladt = new SqlDataAdapter(_sqlcmd);
                    ds1 = new DataSet();
                    _sqladt.Fill(ds1);
                    _sqlcon.Close();

                    chkEmployList.Items.Clear();
                    if(ds1.Tables[0].Rows.Count > 0)
                    chkEmployList.Items.Add("(All)");
                    foreach (DataRow dr in ds1.Tables[0].Rows)
                    {
                        chkEmployList.Items.Add(dr[0], CheckState.Unchecked);
                        //chkEmployList.Items.Add(dr[1],CheckState.Unchecked);      

                    }
                }
                catch (SqlException ex)
                {
                    if (_sqlcon.State == ConnectionState.Open)
                        _sqlcon.Close();
                    LogWrite(ex.Message.ToString());
                }
            }
            else
            {
                SelectEmployee();
            }
        }

        public void LogWrite(string Log)
        {
            try
            {
                string strFileName = "LogFile.txt";
                StreamWriter sWriter = new StreamWriter(strFileName, true);
                DateTime dateTime = DateTime.Now;
                sWriter.WriteLine(dateTime + "\r\t" + Log + "\r\n");
                sWriter.Close();
                sWriter.Dispose();
            }
            catch (Exception ex)
            {
                //NOTHING TO DO....
            }
        }

       

        

      
    }

}
